class RoomsController < ApplicationController
  layout 'main'

  before_filter :correct_agency_required

  # GET /rooms
  # GET /rooms.xml
  def index
    @rooms = Room.find(:all, :conditions => ["site_id = ?", params[:site_id]])

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @rooms }
    end
  end

  # GET /rooms/1
  # GET /rooms/1.xml
  def show
    @room = Room.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @room }
    end
  end

  # GET /rooms/new
  # GET /rooms/new.xml
  def new
    @room = Room.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @room }
    end
  end

  # GET /rooms/1/edit
  def edit
    @room = Room.find(params[:id], :include => :criterias)
  end

  # POST /rooms
  # POST /rooms.xml
  def create
    @room = Room.new(params[:room])
    
    @room.site_id = params[:site_id]
    
    params[:criteria].each_pair do |k,v|
      @room.criterias << Criteria.find(k.to_i) if v == "1"
    end
    
    params[:not_criteria].each_pair do |k,v|
      @room.not_criterias << Criteria.find(k.to_i) if v == "1"
    end
    
    respond_to do |format|
      if @room.save
        flash[:notice] = 'Room was successfully created.'
        format.html { redirect_to agency_site_rooms_path(params[:agency_id], params[:site_id]) }
        format.xml  { render :xml => @room, :status => :created, :location => @room }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @room.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /rooms/1
  # PUT /rooms/1.xml
  def update
    @room = Room.find(params[:id])
    
    @room.criterias.delete_all
    params[:criteria].each_pair do |k,v|
      @room.criterias << Criteria.find(k.to_i) if v == "1"
    end

    @room.not_criterias.delete_all    
    params[:not_criteria].each_pair do |k,v|
      @room.not_criterias << Criteria.find(k.to_i) if v == "1"
    end

    respond_to do |format|
      if @room.update_attributes(params[:room])
        flash[:notice] = 'Room was successfully updated.'
        format.html { redirect_to agency_site_room_path(params[:agency_id], params[:site_id], @room.id) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @room.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /rooms/1
  # DELETE /rooms/1.xml
  def destroy
    @room = Room.find(params[:id])
    @room.destroy

    respond_to do |format|
      format.html { redirect_to(agency_site_rooms_url(params[:agency_id], params[:site_id])) }
      format.xml  { head :ok }
    end
  end
end
